import { login, logout, getInfo, loginWithCheckCode, getDataDicByApp } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  username: '',
  compId: '',
  compName: '',
  avatar: '',
  introduction: '',
  roles: [],
  id: null,
  tenantList: [],
  selectedTenantId: undefined, //当前选中的tenant id
  permissionCodes: [],
  dataDic: undefined
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  },
  SET_TENANTLIST: (state, tenantList) => {
    state.tenantList = tenantList
  },
  SET_SELECTED_TENANTID: (state, selectedTenantId) => {
    state.selectedTenantId = selectedTenantId
  },
  SET_COMPANY_ID: (state, compId) => {
    state.compId = compId
  },
  SET_COMPANY_NAME: (state, compName) => {
    state.compName = compName
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },

  SET_ID: (state, id) => {
    state.id = id
  },
  SET_PERMISSIONCODES: (state, permissionCodes) => {
    state.permissionCodes = permissionCodes
  },
  SET_DATA_DIC: (state, dataDic) => {
    state.dataDic = dataDic
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, appName } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }, appName).then(response => {
        const { content } = response
        commit('SET_TOKEN', content.token)
        setToken(content.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  //后台校验验证码的方式登录!!!
  loginWithCheckCode({ commit }, userInfo) {
    const { username, password, appName, checkCodeKey, checkCodeValue } = userInfo
    return new Promise((resolve, reject) => {
      loginWithCheckCode({ username: username.trim(), password: password, checkCodeKey: checkCodeKey, checkCodeValue: checkCodeValue }, appName).then(response => {
        const { content } = response
        commit('SET_TOKEN', content.token)
        setToken(content.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  //获取app的数据字典
  getDataDic({ commit, state }) {
    return new Promise((resolve, reject) => {
      const appName = process.env.VUE_APP_APP_NAME
      getDataDicByApp(appName).then(response => {
        const { content } = response
        commit('SET_DATA_DIC', content)
        resolve(content)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      const appName = process.env.VUE_APP_APP_NAME
      getInfo(appName).then(response => {
        const { content } = response

        if (!content) {
          reject('get user info failed, please Login again.')
        }
        // {userId: 2, username: "admin", compId: null, compName: null, role: "admin", roles: ["admin"]}
        const { roles, name, username, permissionCodes, tenantList,id } = content

        console.log('谁登录了',response.content)
        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('错误: 用户至少需要关联一个角色!')
        }
        // 用户至少需要设置一个租户
        if (!tenantList || tenantList.length <= 0) {
          reject('错误: 用户至少需要关联一个租户!')
        }
        if (tenantList.length == 1) {//用户只有一个租户, 则默认选中该租户
          state.selectedTenantId = tenantList[0].id
        } else {
          state.selectedTenantId = undefined
        }
        commit('SET_TENANTLIST', tenantList)
        commit('SET_ROLES', roles)
        commit('SET_ID', id)
        commit('SET_PERMISSIONCODES', permissionCodes)
        commit('SET_NAME', name)
        commit('SET_USERNAME', username)
        commit('SET_AVATAR', 'account.png')
        // commit('SET_COMPNAME', compName)
        resolve(content)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
